using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Configuration;

namespace AdminSecurity.Extensions
{

 

internal class AppAuthenticationStateProvider : AuthenticationStateProvider, IHostEnvironmentAuthenticationStateProvider
{
    private Task<AuthenticationState>? _authenticationStateTask;

    private ISecutityAdminService RoleService { get; }

    private string? SimulateUserName { get; }

    //
    // 摘要:
    //     构造函数
    //
    // 参数:
    //   roleService:
    //
    //   configuration:
    public  AppAuthenticationStateProvider(ISecutityAdminService roleService, IConfiguration configuration)
    {
        RoleService = roleService;
        SimulateUserName = configuration["SimulateUserName"];
    }

    //
    // 摘要:
    //     GetAuthenticationStateAsync 方法
    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        AuthenticationState authenticationState = await _authenticationStateTask;
        bool flag = authenticationState.User.Identity?.IsAuthenticated ?? false;
        string authenticationType = authenticationState.User.Identity?.AuthenticationType ?? "Cookies";
        string text = authenticationState.User.Identity?.Name;
        if (!flag && !string.IsNullOrEmpty(SimulateUserName))
        {
            text = SimulateUserName;
            authenticationState = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(new Claim[1]
            {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", SimulateUserName)
            }, authenticationType)));
            _authenticationStateTask = Task.FromResult(authenticationState);
            flag = true;
        }

        if (flag && !string.IsNullOrEmpty(text))
        {
            List<string> roles = RoleService.GetRoles(text);
            if (roles.Any())
            {
                ClaimsIdentity identity = new ClaimsIdentity(authenticationType);
                roles.ForEach(delegate (string roleName)
                {
                    identity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", roleName));
                });
                authenticationState.User.AddIdentity(identity);
            }
        }

        return authenticationState;
    }

    //
    // 摘要:
    //     SetAuthenticationState 方法
    //
    // 参数:
    //   authenticationStateTask:
    public void SetAuthenticationState(Task<AuthenticationState> authenticationStateTask)
    {
        _authenticationStateTask = authenticationStateTask ?? throw new ArgumentNullException("authenticationStateTask");
        NotifyAuthenticationStateChanged(_authenticationStateTask);
    }
}
}